<template>
  <div>
    <BaseForm ref="searchForm" type="search" :items="formItems" v-model:form="searchParams" @search="handleSearch">
      <template #suffix-button>
        <el-button type="primary" @click="handleEdit({})">
          <el-icon>
            <Plus />
          </el-icon>
          添加
        </el-button>
      </template>
    </BaseForm>

    <BaseTable ref="baseTable" :getTableDataFn="wxUserService.getCutomerUserList" :searchParams="searchParams"
      :serial="true">
      <template v-if="props.type == 2">
        <el-table-column prop="wxUserId" label="微信号" />
        <el-table-column prop="wxUserName" label="微信昵称" minWidth="100" />
        <el-table-column prop="url" label="头像">
          <template #default="scope">
            <el-image :preview-teleported="true" :preview-src-list="[scope.row.url]" style="width: 50px; height: 50px"
              v-if="scope.row.url" :src="scope.row.url">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="微信电话" minWidth="100" />
        <el-table-column prop="robotNameList" label="好友机器人" minWidth="100" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="scope.robotNameList">
              {{ scope.robotNameList.join(',') }}
            </span></template>
        </el-table-column>
        <el-table-column prop="wxGroupNameList" label="所属群聊" show-overflow-tooltip minWidth="150">
          <template #default="scope">
            <span v-if="scope.wxGroupNameList">
              {{ scope.wxGroupNameList.join(',') }}
            </span></template>
        </el-table-column>
        <el-table-column prop="selectTagList" label="标签" minWidth="160">
          <template #default="scope">
            <el-tag style="margin-left: 2px; margin-right: 2px; margin-top: 5px" v-for="item in scope.row.selectTagList"
              type="info" :key="item.tagId">
              {{ item.tagName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="realUserName" label="姓名" />
        <el-table-column prop="realPhone" label="电话" show-overflow-tooltip/>
        <el-table-column prop="realAddressInfoList" label="详细家庭地址（用电户号）" minWidth="200">
          <template #default="scope">
            <div style="margin-left: 2px; margin-right: 2px; margin-top: 5px"
              v-for="item in scope.row.realAddressInfoList" type="info" :key="item.tagId">
              <span v-if="getAddress(item).length < 10">{{
                getAddress(item)
              }}</span>
              <el-tooltip v-else class="box-item" effect="dark" :content="getAddress(item)" placement="top">
                <span class="text_ellipsis">{{ getAddress(item) }}</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </template>
      <template v-else>
        <el-table-column prop="realUserName" label="姓名" />
        <el-table-column prop="realPhone" label="电话" />
        <el-table-column prop="realAddressInfoList" label="详细家庭地址（用电户号）" minWidth="200">
          <template #default="scope">
            <div style="margin-left: 2px; margin-right: 2px; margin-top: 5px"
              v-for="item in scope.row.realAddressInfoList" type="info" :key="item.tagId">
              <span v-if="getAddress(item).length < 10">{{
                getAddress(item)
              }}</span>
              <el-tooltip v-else class="box-item" effect="dark" :content="getAddress(item)" placement="top">
                <span class="text_ellipsis">{{ getAddress(item) }}</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="wxUserId" label="微信号" minWidth="100" />
        <el-table-column prop="wxUserName" label="微信昵称" minWidth="100" />

        <el-table-column prop="url" label="头像">
          <template #default="scope">
            <el-image :preview-teleported="true" :preview-src-list="[scope.row.url]" style="width: 50px; height: 50px"
              v-if="scope.row.url" :src="scope.row.url">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="微信电话" minWidth="100" />
        <el-table-column prop="robotNameList" label="好友机器人" show-overflow-tooltip minWidth="100">
          <template #default="scope">
            <span v-if="scope.robotNameList">
              {{ scope.robotNameList.join(',') }}
            </span></template>
        </el-table-column>
        <el-table-column prop="wxGroupNameList" label="所属群聊" minWidth="150" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="scope.wxGroupNameList">
              {{ scope.wxGroupNameList.join(',') }}
            </span></template>
        </el-table-column>
        <el-table-column prop="selectTagList" label="标签" minWidth="160">
          <template #default="scope">
            <el-tag style="margin-left: 2px; margin-right: 2px; margin-top: 5px" v-for="item in scope.row.selectTagList"
              type="info" :key="item.tagId">
              {{ item.tagName }}
            </el-tag>
          </template>
        </el-table-column>
      </template>

      <el-table-column label="操作" fixed="right" width="120">
        <template #default="scope">
          <el-link :underline="false" link type="primary" size="small" @click.prevent="handleEdit(scope.row)">编辑</el-link>

          <el-link :underline="false" link type="primary" size="small"
            @click.prevent="handleLabel(scope.row)">标签设置</el-link>
        </template>
      </el-table-column>
    </BaseTable>
    <labelDialog v-if="visibleLabelDialog" v-model:dialogVisible="visibleLabelDialog" :bizId="bizId" type="1"
      :handleOk="handleLabelOk" :handleCancel="handleLabelCancel"></labelDialog>

    <BaseDialog :title="form.customerId ? `编辑${getTitleName()}` : `新增${getTitleName()}`
      " :handleCancel="handleCancel" v-model:dialogVisible="visibleEditForm">
      <!-- :rules="props.rules" -->
      <el-form class="el-form" ref="addCutomer" label-width="100px" :model="form" :rules="props.rules" @submit="editUser">
        <el-form-item label="关联微信" prop="wxUserId">
          <el-input v-model="form.wxUserName" readonly clearable @click="showWx()" placeholder="请选择关联微信，单选">
            <template #append>
              <el-button @click="clearWx">清除</el-button></template>
          </el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="realUserName">
          <el-input v-model="form.realUserName" placeholder="请输入">
          </el-input>
        </el-form-item>
        <el-form-item label="电话" prop="realPhone">
          <el-input v-model="form.realPhone" placeholder="请输入手机号，多个用、隔开">
          </el-input>
        </el-form-item>
        <el-table border :data="form.realAddressInfoList" :max-height="300" style="width: 100%">
          <el-table-column prop="communityName" label="所属小区" />
          <el-table-column prop="address" label="详细家庭住址" />
          <el-table-column prop="consumerNumber" label="用电户号" />
          <el-table-column label="操作" fixed="right" width="100">
            <template #default="scope">
              <el-link :underline="false" link type="primary" size="small"
                @click.prevent="handleAddEdit(scope.row, scope.$index)">编辑</el-link>

              <el-link :underline="false" link type="danger" size="small"
                @click.prevent="handleDel(scope.$index)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
        <el-button style="width: 100%" type="primary" @click="handleAddEdit()"><el-icon>
            <Plus />
          </el-icon>添加家庭地址、用电户号</el-button>

        <div class="form-btn" style="margin-top: 20px">
          <el-button @click="handleCancel"> 取 消 </el-button>

          <el-button type="primary" :loading="loading" native-type="submit">保存</el-button>
        </div>
      </el-form>
    </BaseDialog>
    <BaseDialog :title="formAdd.isNew ? '添加用电户号' : '编辑用电户号'" :handleCancel="handleAddCancel"
      v-model:dialogVisible="visibleEditFormAdd">
      <el-form class="el-form" ref="addressRef" v-model="formAdd" label-width="100px">
        <el-form-item label="用户电号" prop="realUserName">
          <el-input v-model="formAdd.consumerNumber" placeholder="请输入用电户号，多个用、隔开">
          </el-input>
        </el-form-item>
        <el-form-item label="所属小区">
          <el-select clearable style="width: 100%" filterable v-model="formAdd.communityId"  placeholder="请选择所属小区，单选">
            <el-option v-for="(option, i) of communityList" :key="i" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="详细家庭住址" prop="address">
          <el-input type="textarea" rows="4" maxlength="300" v-model="formAdd.address" placeholder="请输入详细家庭住址，多个用；隔开">
          </el-input>
        </el-form-item>
        <div class="form-btn" style="margin-top: 20px">
          <el-button @click="handleAddCancel"> 取 消 </el-button>

          <el-button type="primary" :loading="loading" @click="editAdd">保存</el-button>
        </div>
      </el-form>
    </BaseDialog>
    <selectWx v-if="dialogVisibleSelectWx" :selectItem="form.wxUserId" :dialogVisible="dialogVisibleSelectWx"
      :optionRobot="optionRobot" :optionGroup="optionGroup" :handleCancel="handleSelectCancel" :handleOk="handleSelectOk">
    </selectWx>
  </div>
</template>

<script setup lang="ts">
import openMsgBox from '@/hooks/messageBox.js'
import { basicConfigService } from '@/api/basicConfig'
import { wxUserService } from '@/api/wxUser'
import { tagService } from '@/api/tag'
import labelDialog from '@/components/labelDialog.vue'
import type { FormInstance } from 'element-plus'
import selectWx from '../components/selectWx.vue'
const communityList = ref([])
const props = defineProps({
  selectItem: {
    type: Object,
  },
  search: {
    type: Function,
  },
  getListFn: {
    type: Function,
  },
  /* 2-敏感客户 3-特殊客户 */
  type: {
    type: Number,
  },
  rules: {
    type: Object,
  },
})
const dialogVisibleSelectWx = ref(false)
const showWx = () => {
  dialogVisibleSelectWx.value = true
}
const handleSelectCancel = () => {
  dialogVisibleSelectWx.value = false
}
const handleSelectOk = (val) => {
  console.log('val=======', val)
  console.log('form.value==========', form.value)
  //customerId
  //form.value.customerId = val.customerId || undefined
  if (val && val.wxUserId != form.value.wxUserId) {
    form.value.wxUserId = val.wxUserId
    form.value.wxUserName = val.wxUserName
    if (!form.value.realUserName && val.realUserName) {
      form.value.realUserName = val.realUserName
    }
    /* 电话要和合并 */
    if (!form.value.realPhone && val.realPhone) {
      form.value.realPhone = val.realPhone
    }
    else if (val.realPhone) {
      form.value.realPhone = form.value.realPhone + '、' + val.realPhone
    }
    if (!form.value.realAddressInfoList) {
      form.value.realAddressInfoList = [];
    }
    if (val.realAddressInfoList)
      form.value.realAddressInfoList = form.value.realAddressInfoList.concat(
        val.realAddressInfoList
      )

  }
  dialogVisibleSelectWx.value = false
}

const getAllCommunity = () => {
  let options = []
  basicConfigService.getAllCommunity({ data: {} }).then((res) => {
    let data = res.data.map((e) => {
      return {
        label: e.communityName,
        value: e.communityId,
      }
    })
    options.push(...data)
  })
  communityList.value = options
}
const router = useRouter()
const getTitleName = () => {
  return props.type == 2 ? '敏感客户' : '特殊客户'
}

/* 2敏感客户 3特殊客户 */
/* const type = computed(() => {
    return router.currentRoute.value.query.type?.toString()
}) */
const optionRobot = ref([])
const optionGroup = ref([])
const formItems = ref([
  {
    name: '微信号',
    key: 'wxUserId',
    type: 'input',
  },
  {
    name: '微信昵称',
    key: 'wxUserName',
    type: 'input',
  },

  {
    name: '姓名',
    key: 'realUserName',
    type: 'input',
  },
  {
    name: '电话',
    key: 'realPhone',
    type: 'input',
  },
  {
    name: '家庭地址',
    key: 'address',
    type: 'input',
  },
  {
    name: '用电户号',
    key: 'consumerNumber',
    type: 'input',
  },
  {
    name: '好友机器人',
    key: 'robotWxId',
    type: 'select',
    options: optionRobot,
  },
  {
    name: '所属群聊',
    key: 'wxGroupCode',

    type: 'select',
    options: optionGroup,
  },
  {
    name: '标签搜索',
    key: 'tagIds',
    type: 'label',
    selecedList: [],
    tagType: 1, //1：用户标签
  },
])
const searchParams = ref({
  wxUserId: '',
  wxUserName: '',
  wxUserRemark: '',
  phone: '',
  realUserName: '',
  realPhone: '',
  address: '',
  isSensitive: props.type == 2 ? 1 : '',
  isSpecial: props.type == 3 ? 1 : '',
  tagIds: [],
})
const form = ref({
  realUserName: '',
  realPhone: '',
  realAddressInfoList: [],
  customerId: '',
  wxUserId: '',
  wxUserName: '',
})
const loading = ref(false)
onMounted(() => {
  getAllCommunity()
  getAllGroup()
  getAllRobot()
})
const getAllGroup = () => {
  basicConfigService
    .pageListWxGroupResDto({ data: {}, pageSize: 999999, pageNumber: 1 })
    .then((res) => {
      optionGroup.value = res.data.content.map((n) => {
        return { label: n.wxGroupName, value: n.wxGroupCode }
      })
    })
}
const getAllRobot = () => {
  basicConfigService
    .pageListRobotResDto({ data: {}, pageSize: 999999, pageNumber: 1 })
    .then((res) => {
      optionRobot.value = res.data.content.map((n) => {
        return { label: n.managerName, value: n.wxRobotId }
      })
    })
}

const baseTable = ref(null)
const sortTablekey = ref(1)
const getAddress = (row) => {
  if (row.consumerNumber) return `${row.address}（ ${row.consumerNumber} ）`
  else return row.address
}

const handleSearch = (data = { sort: undefined }, e = '') => {
  if (e != 'sort') sortTablekey.value = 0
  baseTable.value.handleSearch({
    ...searchParams.value,
    isSensitive: props.type == 2 ? 1 : '',
    isSpecial: props.type == 3 ? 1 : '',
    // tagIds: searchParams.value.tagIds?.map((n) => n.tagId),
    selecedList: undefined,
    updateTimeOrder: data?.sort,
  })
}

const handleLabelOk = (e) => {
  tagService
    .addTagRelation({
      data: {
        bizId: wxUserId.value ? wxUserId.value : customerId.value,
        type: 1,
        // tagIdList: e ? e.map((n) => n.tagId) : [],
        tagIdList: e.map((n) => n.tagId) || [],
      },
    })
    .then((res) => {
      visibleLabelDialog.value = false
      handleSearch()
    })
}
const handleLabelCancel = () => {
  visibleLabelDialog.value = false
}
const visibleLabelDialog = ref(false)
const wxUserId = ref('')
const customerId = ref('')
const bizId = ref('')
const handleLabel = (row) => {
  wxUserId.value = row.wxUserId
  customerId.value = row.customerId
  bizId.value = row.wxUserId ? row.wxUserId : row.customerId

  visibleLabelDialog.value = true
}
const tableData = ref([])
const visibleEditForm = ref(false)
const handleEdit = (row) => {
  if (!row.customerId) {
    form.value = {
      realUserName: '',
      realPhone: '',
      realAddressInfoList: [],
      customerId: '',
      wxUserId: '',
      wxUserName: '',
    }
  } else {
    form.value = JSON.parse(JSON.stringify(row))
  }
  console.log(form.value, 99999999999)

  if (!form.value.realAddressInfoList) {
    console.log()

    form.value.realAddressInfoList = []
  }
  //tableData.value=form.value.
  visibleEditForm.value = true
}
const addressRef = ref<FormInstance>()
const addCutomer = ref<FormInstance>()
const editUser = (e) => {
  e.preventDefault()
  addCutomer.value.validate((valid, fields) => {
    if (valid) {
      loading.value = true

      wxUserService
        .editWxUser({
          data: {
            customerId: form.value.customerId,
            wxUserId: form.value.wxUserId,
            realUserName: form.value.realUserName,
            realPhone: form.value.realPhone,
            sourceType: props.type,
            realAddressInfoList: form.value.realAddressInfoList,
          },
        })
        .then((res) => {
          ElMessage({
            message: '保存成功',
            type: 'success',
          })

          loading.value = false
          visibleEditForm.value = false
          handleSearch()
        })
        .catch(() => {
          loading.value = false
        })
    }
  })
}
const clearWx = () => {
  form.value.wxUserId = ''
  form.value.wxUserName = ''
}
const handleCancel = () => {
  visibleEditForm.value = false
}
const handleDel = (index) => {
  openMsgBox(
    {},
    () => {
      form.value.realAddressInfoList.splice(index, 1)
    },
    () => {
      //handleSearch()
    }
  )
}
const formAdd = ref({
  consumerNumber: '',
  communityId: '',
  communityName: '',
  address: '',
  isNew: 0,
})
const visibleEditFormAdd = ref(false)
const temIndex = ref(0)
const handleAddEdit = (row?, index?) => {
  if (row) {
    formAdd.value = { ...row, isNew: 0 }
    temIndex.value = index
  } else {
    formAdd.value = {
      consumerNumber: '',
      communityId: '',
      communityName: '',
      address: '',
      isNew: 1,
    }
  }
  visibleEditFormAdd.value = true
}
const handleAddCancel = () => {
  visibleEditFormAdd.value = false
}
const editAdd = () => {
  if (!formAdd.value.consumerNumber && !formAdd.value.address) {
    ElMessage({
      message: '用电户号和详细家庭住址至少必填一个',
      type: 'error',
    })
    return
  }
  console.log(form.value.realAddressInfoList)
  if(formAdd.value.communityId){
    formAdd.value.communityName=communityList.value.find((n)=>n.value==formAdd.value.communityId)?.label
  }
  else{
    formAdd.value.communityName=''
  }

  if (formAdd.value.isNew) {
    form.value.realAddressInfoList.push(formAdd.value)
  } else {
    form.value.realAddressInfoList.splice(temIndex.value, 1, formAdd.value)
  }
  visibleEditFormAdd.value=false;



}
</script>

<style lang="less" scoped></style>
